/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 线路分析 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: "unit.+",
		step2:"unit",
		auto_save: "No",
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
	}
	
	var steplist = GEN.getStepList({job:job})
	steplist = steplist.filter(function(v){
		var tmpreg = new RegExp(par.step,"ig")
		return tmpreg.test(v)
	})
	if (steplist.length == 0 && par.step2) {
		steplist = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	steplist.forEach(function(step) {
		GEN.openStep({job:job, name:step})
        GEN.units({type:"mm"})

        if(GEN.isChklistExists({job:job,step:step,chklist:'checklist'})){
            GEN.COM("chklist_delete,chklist=checklist")
        }
        GEN.COM("chklist_create,chklist=checklist")
        GEN.COM("chklist_show,chklist=checklist")
		GEN.COM("chklist_single,action=valor_analysis_signal,show=yes")
		GEN.COM("chklist_erf,chklist=valor_analysis_signal,nact=1,erf=Inner (Mils)")
        GEN.COM("chklist_pclear")
        GEN.COM("chklist_cupd,chklist=valor_analysis_signal,nact=1,params=((pp_layer=.type=signal|mixed&side=inner)(pp_spacing=203)(pp_r2c=381)(pp_d2c=356)(pp_sliver=254)(pp_min_pad_overlap=127)(pp_tests=Spacing\;Drill\;Rout\;Size\;Sliver\;Stubs\;Center\;SMD\;Bottleneck\;Pad Connection Check)(pp_selected=All)(pp_check_missing_pads_for_drills=No)(pp_use_compensated_rout=No)(pp_sm_spacing=No)),mode=regular")
        GEN.COM("chklist_pcopy,chklist=valor_analysis_signal,nact=1")
        GEN.COM("chklist_ppaste,chklist=checklist,row=0")
        GEN.COM("chklist_close,chklist=valor_analysis_signal,mode=hide")
        GEN.COM("chklist_cupd,chklist=checklist,nact=1,params=((pp_layer=.type=signal|mixed&side=inner)(pp_spacing=203)(pp_r2c=381)(pp_d2c=356)(pp_sliver=254)(pp_min_pad_overlap=127)(pp_tests=Spacing\;Drill\;Rout\;Size\;Sliver\;Stubs\;Center\;SMD\;Bottleneck\;Pad Connection Check)(pp_selected=All)(pp_check_missing_pads_for_drills=No)(pp_use_compensated_rout=No)(pp_sm_spacing=No)),mode=regular")
        GEN.COM("chklist_run,chklist=checklist,nact=1,area=local")
        GEN.COM("chklist_res_show,chklist=checklist,nact=1,x=0,y=0,w=0,h=0")

	})
	
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}
